package com.lx.controller;

import com.lx.entity.Product;
import com.lx.service.ProductService;
import com.lx.service.RedisService;
import com.lx.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class FavoriteController {
    @Autowired
    private RedisService redisService;
    @Autowired
    private ProductService productService;

    @PostMapping("/collection/add")
    @ApiOperation(value = "添加商品到收藏夹", notes = "用户收藏商品，最多6个")
    public Result addToFavorite(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("userId");
        Integer productId = (Integer) params.get("productId");

        if (userId == null || productId == null) {
            return Result.error(5500, "用户ID或商品ID不能为空");
        }

        boolean result = redisService.addToFavorite(userId, productId);
        if (result) {
            return Result.success(5200, "收藏成功");
        } else {
            return Result.error(5500, "该商品已收藏");
        }
    }

    @PostMapping("/collection/remove")
    @ApiOperation(value = "移除收藏商品", notes = "从收藏夹中移除指定商品")
    public Result removeFromFavorite(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("userId");
        Integer productId = (Integer) params.get("productId");

        if (userId == null || productId == null) {
            return Result.error(5500, "用户ID或商品ID不能为空");
        }

        boolean result = redisService.removeFromFavorite(userId, productId);
        if (result) {
            return Result.success(5200, "移除成功");
        } else {
            return Result.error(5500, "未找到该商品");
        }
    }

    @PostMapping("/collection/list")
    @ApiOperation(value = "获取用户收藏列表", notes = "返回用户所有收藏的商品")
    public Result getFavoriteList(@RequestBody Map<String, Object> params) {
        Integer userId = (Integer) params.get("userId");
        if (userId == null) {
            return Result.error(5500, "用户ID不能为空");
        }

        List<Integer> productIds = redisService.getFavoriteList(userId);
        List<Product> products = new ArrayList<>();

        if (productIds != null && !productIds.isEmpty()) {
            for (Integer id : productIds) {
                Product product = productService.getProductById(id);
                if (product != null) {
                    products.add(product);
                }
            }
        }

        return Result.success(5200, "获取成功").add("products", products);
    }
}
